/// <reference path="../../../modules/jquery/jquery-2.1.3.js" />
/// <reference path="rsa.js" />
define([ "PDLoginDir/js/rsa", "jquery", "JQuery.validate",
		"JQuery.validate.message", "JQuery.validate.extra" ], function(rsa) {
	/*
	 * 全局表单验证
	 */
	$.validator.setDefaults({
		errorElement : 'span',
		highlight : function(target) {
			var fg = $(target).closest('.guide_item');
			// 直接是输入框时，修改输入框的边框样式，比如table中的输入框验证
			fg.addClass('has_error');
		},
		success : function(message) {
			var fg = message.closest('.guide_item');
			fg.length && fg.removeClass('has_error');
			message.remove();
		}
	});
	// 监听focus事件
	$(".guide_item").on("focusin", function() {
		$(this).addClass("has_focus");
	})
	$(".guide_item").on("focusout", function() {
		$(this).removeClass("has_focus");
	})

	// 配置validate
	var ret = {
		// 成员变量
		// 登录名录入框选择器
		inputLoginNameSelector : "#pd_web_login_name",
		// 密码录入框选择器
		inputPwdSelector : "#pd_web_pwd",

		inputPhoneSelector : "#pd_web_phone",
		inputEmailSelector : "#pd_web_email",
		inputQuestionSelector : "#pd_web_question",
		inputAnswerSelector : "#pd_web_answer",

		btnSubmitSelector : '#pd_web_btn_submit',
		formSelector : "#pd_web_guide_form",
		_tabsLength : 0,
		_curFocus : 0,
		_enterSubmit : true,
		validator : undefined
	};
	ret._onfocus = function(evt) {
		// /<summary>焦点事件</summary>
		this._curFocus = parseInt($(evt.target).attr("tabindex"));
		if (this._curFocus > this._tabsLength - 1 || this._curFocus < 0) {
			this._curFocus = 0;
		}
		this._enterSubmit = true;// 可以回车提交
	};
	ret._initFocus = function() {
		// /<summary>初始化焦点 </summary>
		var s = this.formSelector + " " + ":input,button";
		var inputs = $(s);
		inputs.focus(this._hitch(this, this._onfocus));
		for (var i = 0; i < inputs.length; i++) {
			var it = inputs[i];
			if ($(it).val().length == 0) {
				$(it).focus();
				this._curFocus = i;
				break;
			}
		}
	};
	ret._initTabindex = function() {
		// /<summary>初始化tab键顺序 </summary>
		var s = this.formSelector + " " + ":input,button";
		var inputs = $(s);
		for (var i = 0; i < inputs.length; i++) {
			var it = inputs[i];
			$(it).attr("tabindex", i + 1);
			this._tabsLength++;
		}
	};
	ret._getCurFocusId = function() {
		// /<summary>获得现在的焦点element id </summary>
		var s = this.formSelector + " [" + "tabindex=" + "'" + this._curFocus
				+ "'" + "]";
		var r = $(s);
		s = r.attr("id");
		if (s == document.activeElement.id) {
			return s;
		}

		return "";
	};
	ret._hitch = function(/* Object */scope, /* Function|String */method) {
		return function() {
			return method.apply(scope, arguments || []);
		}; // Function
	};
	ret.onkeyUpEvt = function(evt, elm) {
		// /<summary>键盘up键事件</summary>
		// /<param name="evt" type='KeyboardEvent'></param>
		if (evt.keyCode == 13) {
			$(this.btnSubmitSelector).trigger("click");
			// var sId = this._getCurFocusId()
		}
	};
	ret.Init = function() {
		// /<summary>初始化函数 </summary>
		this._initFocus();
		this._initTabindex();
		this.initValidate();
		$(this.formSelector).keyup(this._hitch(this, this.onkeyUpEvt));
		$(this.btnSubmitSelector).unbind();
		$(this.btnSubmitSelector).on("click", this._hitch(this, this.onLoginSubmit));
		$("#pd_web_login_name").change( this._hitch(this, this.onUserCodeChanged));
	};
	ret.initValidate = function() {
		// /<summary>初始化校验参数 </summary>
		this.validator = $(this.formSelector).validate({
			rules : {
				pd_web_login_name : {
                    required:true
                },
				pd_web_pwd : {
                    required:true,
                    PD_password: true
                },
				pd_web_phone : {
                    required:true,
                    PD_mobile: true
                },
				pd_web_email : {
					required:true,
					email:true
				},
				pd_web_question : {
                    required:true
                },
				pd_web_answer : {
                    required:true
                }
			},
			messages : {
				pd_web_login_name : {
                    required: "请填写登录名"
                },
				pd_web_pwd : {
                    required: "请填写密码"
                },
				pd_web_phone : {
                    required: "请填写电话号码"
                },
				pd_web_email : {
                    required: "请填写电子邮箱"
                },
				pd_web_question : {
                    required: "请填写问题"
                },
				pd_web_answer : {
                    required: "请填写答案"
                }
			},
			errorPlacement : this._hitch(this, this.onValidatePlacement),
			Onubmit : false,
			onfocusout : false,
			onkeyup : false,
			onclick : false
		})
	};
	ret._validateEach = function() {
		var s = this.formSelector + " input," + this.formSelector + " select";
		var inputs = $(s);
		var b = true;
		var bFirstFinded = false;
		for (var i = 0; i < inputs.length; i++) {
			var it = inputs[i];
			b = this.validator.element(it)
			if (!b && !bFirstFinded) {
				$(it).focus();
				bFirstFinded = true;
			}
		}
		return !bFirstFinded;
	}
	ret.onValidatePlacement = function(error, element) {
		$(element).closest(".guide_item").find(".error").append(error);
	};
	ret.onRefreshCaptcha = function() {
		// /<summary>校验码刷新事件</summary>
		// /String.valueOf(random());
		var s = Math.round(Math.random() * 10000).toString();
		s = this._captchaUrl + "&r=" + s;
		if (this.captchaHeight > 0 && this.captchaWidth > 0)
			s += "&width=" + this.captchaWidth.toString() + "&height="
					+ this.captchaHeight.toString();
		$(this.imgCaptchaSelector).attr("src", s);
		$(this.inputCaptchaSelector).val("");
	};
	ret.onPostCheckPwdSuccess = function(data) {
		if (data.status == 200) {
			window.location.href = getServer()
					+ "/flea/hclv/guide/toLogin.htmls";
			$(this.btnSubmitSelector).html("验证通过");
		} else {
			// alert(data.message);
			// console.log(data.message);
			$(this.btnSubmitSelector).html("登录").removeClass("disabled");
			this._enterSubmit = true;
		}
	};
	ret.onPostCheckPwdError = function(data) {
		$(this.btnSubmitSelector).html("请求异常").removeClass("disabled");
		this._enterSubmit = true;
	};
	// 监听登录按钮点击事件
	ret.onLoginSubmit = function() {
		if (this._enterSubmit) {
			this._enterSubmit = false;
			if (this._validateEach()) {
				$(this.btnSubmitSelector).html("请求中……").addClass("disabled");
//				var rsaKey = rsa.getKeyPair(rsaKeyExponent, "", rsaKeyModulus);
				var d = {
					"username" : $(this.inputLoginNameSelector).val(),
					"password" : $(this.inputPwdSelector).val(),
					"phone" : $(this.inputPhoneSelector).val(),
					"email" : $(this.inputEmailSelector).val(),
					"question" : $(this.inputQuestionSelector).val(),
					"answer" : $(this.inputAnswerSelector).val(),
					"code" : $(this.inputCaptchaSelector).val()
				}
				// 传递登录返回的地址
				if (redirectUrl && redirectUrl.length > 0
						&& redirectUrl != 'null') {
					d.redirectUrl = encodeURI(redirectUrl);
				}
				$.ajax({
					global : false,// 禁用全局ajax事件
					url : getServer()
							+ "/flea/hclv/guide/account/register.htmls",
					data : d,
					success : this._hitch(this, this.onPostCheckPwdSuccess),
					error : this._hitch(this, this.onPostCheckPwdError)
				})
			}
			;
		}
	};
	ret.onUserCodeChanged = function(evt) {
		$("#pd_web_pwd").val("");
		$("#pd_web_check_pwd").removeAttr("checked");
	}
	return ret;
})